package com.ygglxt.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 定义过滤器名称和定义过滤路径
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter { // 实现javax.servlet下的Filter

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    // 重写其中的doFilter方法
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //2.将参数servlet转为http形式,因为下面要操作session
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //3.获取当前访问的URL，用以判断是否直接放行
        String requestURI = request.getRequestURI();
        //4.定义直接放行的资源请求(根据自己实际情况定义放行的资源)
        if(requestURI.contains("AdminServlet")||requestURI.contains("static")||requestURI.contains("/")||requestURI.contains("login")){
            //如果匹配成功，则放行
            filterChain.doFilter(request, response);
            return;
        }
        //7.捕获到需要过滤的请求，检查是否有登录后赋予的session（检查是否已登录）
        if (request.getSession().getAttribute("admin")!=null) { //“login”是登录接口定义的session名
            filterChain.doFilter(request, response);
            return;
        }

        //8.如果无session，登录失败，可以给予前端一些提示
        response.sendRedirect("/login.jsp");
    }

    @Override
    public void destroy() {

    }

}